package com.baizan.daka.rx.Subscriber

import android.util.Log
import com.baizan.daka.net.HttpResult
import com.hazz.kotlinmvp.net.BaseResponse
import com.hazz.kotlinmvp.net.exception.HttpStatus
import io.reactivex.Observer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import retrofit2.HttpException
import java.net.SocketTimeoutException


abstract class BaseSubscriber<T>(val mCompositeSubscription: CompositeDisposable? = CompositeDisposable()) :
    Observer<BaseResponse<T>>, HttpResult<T> {
    var disposable: Disposable? = null
    override final fun onSubscribe(d: Disposable) {
        this.disposable = d
        mCompositeSubscription?.add(d)
    }

    override final fun onNext(t: BaseResponse<T>) {
        if (t.code == HttpStatus.SUCCESS) {
            onCallNext(t.data)
        } else if (t.code == HttpStatus.FAIL) {
            onCallError(t.msg)
        } else if(t.code == HttpStatus.LOGIN_ERROR){
            onCallLogin(t.msg)
        }
        onComplete()
    }

    override final fun onError(e: Throwable) {
        Log.e("onError", "" + e.message)
        if (e is HttpException)
            onCallError("服务异常 ${e.message}")
        else if (e is SocketTimeoutException)
            onCallError("网络连接超时")
        else
            onCallError(e.message ?: "抱歉程序开了个小差，正在修理它!")
        onComplete()
    }

    override final fun onComplete() {
        if (disposable?.isDisposed()!!) {
            disposable?.dispose()
        }
        onCallCompleted()
    }
}